<!--
 * @Author: your name
 * @Date: 2020-03-21 18:52:34
 * @LastEditTime: 2020-05-06 23:52:41
 * @LastEditors: Please set LastEditors
 * @Description: In User Settings Edit
 * @FilePath: \museweb\src\views\musePage\frontPage\recommendationList.vue
 -->
<template>
    <d2-container>
        <div class="muse_table_box">
            <div class="muse_control_box">
                <el-button class="muse_float_left" type="primary" @click="addData">添加</el-button>
                <el-button class="muse_float_left" type="primary" @click="fnSort">排序</el-button>
            </div>
            <el-table
                    :data="showData"
                    style="width: 100%"
                    :row-key="getRowkey"
                    @selection-change="handleSelectionChange">
                <el-table-column prop="type" label="类型">
                    <template slot-scope="scope">
                        {{ scope.row.type === 'product'?'商品': scope.row.type === 'store' ? '门店' : scope.row.type === 'dish' ? '菜品' : scope.row.type === 'activity' ? '活动' : '兑换券' }}
                    </template>
                </el-table-column>
                <el-table-column label="名称">
                  <template slot-scope="scope">
                    {{ scope.row[scope.row.type].name || scope.row[scope.row.type].title }}
                        <!-- {{ scope.row.type === 'product'? scope.row.product.name : scope.row.store.name}} -->
                    </template>
                </el-table-column>
                <el-table-column
                        fixed="right"
                        label="操作"
                        width="120">
                    <template slot-scope="scope">
                        <el-button @click="deleteRow(scope.row)" type="text" size="small">删除</el-button>
                    </template>
                </el-table-column>
            </el-table>
        </div>

        <el-dialog title="添加推荐" :visible="dialogDataVisible" :show-close="false">
            <el-form ref="detailForm" :model="detailForm" :rules="rules" label-width="100px">
              <el-form-item label="类型" prop="type">
                  <el-select style="width:100%;" v-model="detailForm.type" placeholder="请选择展示类型">
                      <el-option
                              v-for="item in recommendType"
                              :key="item.value"
                              :label="item.label"
                              :value="item.value">
                      </el-option>
                  </el-select>
              </el-form-item>
              <el-form-item label="商品" prop="productName" v-if="detailForm.type === 'product'">
                  <el-input placeholder="商品" v-model="detailForm.productName" readonly @focus="fnOpenPopup"></el-input>
              </el-form-item>
              <el-form-item label="门店" prop="storeName" v-if="detailForm.type === 'store'">
                  <el-input placeholder="商品" v-model="detailForm.storeName" readonly @focus="fnOpenPopup"></el-input>
              </el-form-item>
              <el-form-item label="菜品" prop="dishName" v-if="detailForm.type === 'dish'">
                  <el-input placeholder="菜品" v-model="detailForm.dishName" readonly @focus="fnOpenPopup"></el-input>
              </el-form-item>
              <el-form-item label="活动" prop="activityName" v-if="detailForm.type === 'activity'">
                  <el-input placeholder="活动" v-model="detailForm.activityName" readonly @focus="fnOpenPopup"></el-input>
              </el-form-item>
              <el-form-item label="兑换券" prop="voucherName" v-if="detailForm.type === 'voucher'">
                  <el-input placeholder="兑换券" v-model="detailForm.voucherName" readonly @focus="fnOpenPopup"></el-input>
              </el-form-item>
              <el-form-item >
                  <el-button type="primary" @click="submitForm('detailForm')">确定</el-button>
                  <el-button @click="resetForm('detailForm')">取消</el-button>
              </el-form-item>
            </el-form>
        </el-dialog>

        <el-dialog :title="detailForm.type === 'product'?'商品列表':'门店列表'" :visible="dialogDataList" :show-close="false">
            <el-table :data="tableData"
                      width="100%"
                      ref="ref_table"
                      highlight-current-row
                      @current-change="handleRadioTable">
                <el-table-column prop="name" label="名称"/>
                <el-table-column prop="brief" label="简介">
                    <template slot-scope="{row: {brief}}">
                        <span>{{brief | subStr(10)}}</span>
                    </template>
                </el-table-column>
            </el-table>
            <el-pagination
                    class="muse_pagination"
                    :background="true"
                    @size-change="handleSizeChange"
                    @current-change="handleCurrentChange"
                    :current-page="paging.page"
                    :page-sizes="paging.pageSizeAry"
                    :page-size="paging.pageSize"
                    layout="total, sizes, prev, pager, next, jumper"
                    :total="paging.total">
            </el-pagination>
            <span slot="footer" class="dialog-footer">
                <el-button @click="fnClosePopup">取 消</el-button>
                <el-button type="primary" @click="fnSaveChoosed">确 定</el-button>
            </span>
        </el-dialog>

        <el-dialog :title="detailForm.type === 'dish'?'菜品列表': detailForm.type === 'voucher' ? '兑换券列表' :'活动列表'" :visible="dialogDataListTwo" :show-close="false">
            <el-table :data="tableData"
                      width="100%"
                      ref="ref_table"
                      highlight-current-row
                      @current-change="handleRadioTable">
                <el-table-column prop="title" label="名称"/>
            </el-table>
            <el-pagination
                    class="muse_pagination"
                    :background="true"
                    @size-change="handleSizeChange"
                    @current-change="handleCurrentChange"
                    :current-page="paging.page"
                    :page-sizes="paging.pageSizeAry"
                    :page-size="paging.pageSize"
                    layout="total, sizes, prev, pager, next, jumper"
                    :total="paging.total">
            </el-pagination>
            <span slot="footer" class="dialog-footer">
                <el-button @click="fnClosePopup">取 消</el-button>
                <el-button type="primary" @click="fnSaveChoosed">确 定</el-button>
            </span>
        </el-dialog>
    </d2-container>
</template>

<script>
  import tableMixin from '../mixins/tableMixin'
  import { getPageRecommendation, addRecommendationItem, deleteRecommendationItem, changeRecommendation, getProductList, getStoreList, getDishList, getActivitylist, getVoucherList } from '@/api/admin'
  import { recommendType } from '@/config/common.data'
  import Sortable from 'sortablejs'
  export default {
    name: 'activityList',
    mixins: [tableMixin],
    data () {
      return {
        recommendType,
        dialogDataVisible: false,
        dialogDataList: false,
        dialogDataListTwo: false,
        tableData: [],
        showData: [],
        detailForm: {
          type: '',
          product: '',
          productName: '',
          store: '',
          storeName: '',
          dish: '',
          dishName: '',
          activity: '',
          activityName: '',
          voucher: '',
          voucherName: '',
          page: 'mall',
        },
        imageUrl: '',
        rules: {
          type: [
            { required: true, message: '请选择类型', trigger: 'blur' }
          ],
          productName: [
            { required: true, message: '请选择商品', trigger: 'blur' }
          ],
          storeName: [
            { required: true, message: '请选择门店', trigger: 'blur' }
          ],
          dishName: [
            { required: true, message: '请选择菜品', trigger: 'blur' }
          ],
          activityName: [
            { required: true, message: '请选择活动', trigger: 'blur' }
          ],
          voucherName: [
            { required: true, message: '请选择兑换券', trigger: 'blur' }
          ]
        },
        choosedDataObj: {}
      }
    },
    created () {
      this.getPageRecommendation()
    },
    mounted() {
        this.rowDrop()
    },
    methods: {
      rowDrop() {
        const tbody = document.querySelector('.el-table__body-wrapper tbody')
        const _this = this
        Sortable.create(tbody, {
          onEnd({ newIndex, oldIndex }) {
            const currRow = _this.showData.splice(oldIndex, 1)[0]
            _this.showData.splice(newIndex, 0, currRow)
          }
        })
      },
      addData() {
        this.dialogDataVisible = true
        this.$refs['detailForm'].resetFields()
      },
      // 表单提交
      submitForm (formName) {
        this.$refs[formName].validate(async (valid) => {
          if (valid) {
            const params = {
              page: this.detailForm.page,
              detail: {
                type: this.detailForm.type,
                [this.detailForm.type]: this.detailForm[this.detailForm.type]
              }
            }
            // this.detailForm.type === 'product' ? this.detailForm.product : this.detailForm.store
            const res = await addRecommendationItem(params)
            this.dialogDataVisible = false
            this.getPageRecommendation()
          } else {
            return false;
          }
        });
      },
      // 表单重置
      resetForm (formName) {
        this.$refs[formName].resetFields()
        this.dialogDataVisible = false
      },
      async getPageRecommendation() {
        const params = {
          page: 'mall'
        }
        const { code, data: { detail } } = await getPageRecommendation(params)
        this.showData = detail
      },
      // 删除该行
      deleteRow(row) {
        this.wrapConfirm(4).then( async () => {
          const params = {
            page: 'mall',
            detail: {
              type: row.type,
              [row.type]: row[row.type]._id
            }
          }
          const res =  await deleteRecommendationItem(params)
          this.getPageRecommendation()
        }).catch(() => {})
      },
      // 得到key
      getRowkey(row) {
        console.log(row)
        return row[row.type]._id
      },
      // 排序
      async fnSort() {
        const tempList = []
        this.showData.forEach(item => {
          tempList.push({
            type: item.type,
            [item.type]: item[item.type]._id
          })
        })
        const params = {
          page: 'mall',
          detail: tempList
        }
        const res = await changeRecommendation(params)
        this.$message({
          message: '排序成功',
          type: 'success'
        });
      },

      // 打开链接弹框
      fnOpenPopup () {
        if(this.detailForm.type === 'store' || this.detailForm.type === 'product') {
          this.dialogDataList = true
        } else {
          this.dialogDataListTwo = true
        }
        this.tableData = []
        this.paging = {
          total: 0,
          page: 1
        }
        this.getTableData()
      },
      fnClosePopup () {
        this.dialogDataList = false
         this.dialogDataListTwo = false
        this.choosedDataObj = {}
      },
      // 获得链接列表
      async getTableData(value, type) {
        let params = {
          page: type === 'page'? (value ? value : this.paging.page) : this.paging.page,
          pageSize: type === 'pageSize'? (value ? value : this.paging.pageSize) : this.paging.pageSize
        }
        
        const { code, data: { total, currentPage, data, pageSize } } = this.detailForm.type=== 'product' ? await getProductList(params) : this.detailForm.type=== 'store'? await getStoreList(params) : this.detailForm.type=== 'dish' ? await getDishList(params) : this.detailForm.type=== 'activity' ?  await getActivitylist(params) : await getVoucherList(params)
        this.paging.total = total
        this.paging.pageSize = pageSize
        this.paging.page = currentPage
        this.tableData = data
      },
      handleRadioTable(value) {
        this.choosedDataObj = value
      },
      fnSaveChoosed () {
        this.detailForm.product = ''
        this.detailForm.productName = ''
        this.detailForm.store = ''
        this.detailForm.storeName = ''
        this.detailForm.dish = ''
        this.detailForm.dishName = ''
        this.detailForm.activity = ''
        this.detailForm.activityName = ''
        this.detailForm.voucherName = ''
        if(this.detailForm.type === 'product') {
          this.detailForm.product = this.choosedDataObj._id
          this.detailForm.productName = this.choosedDataObj.name
        } else if(this.detailForm.type === 'store') {
          this.detailForm.store = this.choosedDataObj._id
          this.detailForm.storeName = this.choosedDataObj.name
        } else if(this.detailForm.type === 'dish') {
          this.detailForm.dish = this.choosedDataObj._id
          this.detailForm.dishName = this.choosedDataObj.title
        } else if(this.detailForm.type === 'activity') {
          this.detailForm.activity = this.choosedDataObj._id
          this.detailForm.activityName = this.choosedDataObj.title
        } else {
          this.detailForm.voucher = this.choosedDataObj._id
          this.detailForm.voucherName = this.choosedDataObj.title
        }
        this.fnClosePopup()
      }
    }
  }
</script>

<style scoped>

</style>
